import { useViewportStore } from '@/store/viewport'
import { storeToRefs } from 'pinia'
import { Box3, Sphere, Vector3 } from 'three'
import { gsap } from 'gsap'
export const useFocusObject = () => {
  // 聚焦
  const box = new Box3()
  const center = new Vector3()
  const sphere = new Sphere()
  const viewportStore = useViewportStore()
  const { camera, orbitControls } = storeToRefs(viewportStore)
  function focusObject (obj, dis = 500, duration = 0.5) {
    if (obj) {
      box.setFromObject(obj)
      let distance
      if (box.isEmpty() === false) {
        box.getCenter(center)
        distance = box.getBoundingSphere(sphere).radius
      } else {
        center.setFromMatrixPosition(obj.matrixWorld)
        distance = 0.1
      }
      if (camera.value && orbitControls.value) {
        gsap.to(orbitControls.value.target, {
          duration,
          ...center
        })
        gsap.to(camera.value.position, {
          duration,
          ...center.add(new Vector3(-Math.max(distance * 1.2, dis), Math.max(distance / 2, dis), 0))
        })
        camera.value.lookAt(center)
      }
    }
  }

  return { focusObject }
}
